package com.ody.util.code;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author WuBo
 * @CreateDate 2013-12-6
 */
public class VersionUtils {
	private final static int PRECISION = 2;
	
	/**
	 * 检查版本号是否是符合要求的版本号
	 * @author WuBo
	 * @CreateDate 2012-4-1 上午09:42:47
	 * @param version
	 * @param bits 版本号位数，-1表示不限制位数
	 * @return
	 */
	public static boolean checkVersion(String version, int bits){
		if(version==null || version.trim().equals("")){
			return false;
		}
		String regex = "^(\\d{1,"+PRECISION+"})(\\.\\d{1,"+PRECISION+"}){"+(bits-1)+"}$";
		if(bits == -1){
			regex = "^(\\d{1,"+PRECISION+"})(\\.\\d{1,"+PRECISION+"})*$";
		}
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher=pattern.matcher(version);
		return matcher.matches();
	}

	/**
	 * 转换版本号到长整型，版本号格式：数字[.数字]{bits}
	 * @author WuBo
	 * @CreateDate 2012-4-1 上午09:45:37
	 * @param version
	 * @param bits 位数
	 * @return
	 * @throws Exception
	 */
	public static Long convert2Long(String version, int bits) throws Exception {
		if (! checkVersion(version, bits)) {
			throw new Exception("提示：无效的版本号！");
		}
		String[] versionArray = version.split("[.]");
		Long version_long;
		try {
			StringBuilder verstr = new StringBuilder();
			for (String t : versionArray) {
				for (int i = t.length(); i < PRECISION; i++) {
					verstr.append(0);
				}
				verstr.append(t);
			}
			version_long = Long.parseLong(verstr.toString());
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("提示：无效的版本号！");
		}
		return version_long;
	}

}